package Stackdemo;

import java.util.Stack;

public class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;
    public MinStack() {
        this.stack = new Stack<>();
        this.minStack = new Stack<>();
    }

    public void push(int val) {
        if(stack.isEmpty()){
            stack.push(val);
            minStack.push(val);
        }else{
            stack.push(val);
            if(val<=minStack.peek()){
                minStack.push(val);
            }
        }
    }

    public void pop() {
        if(stack.isEmpty()){
            return;
        }
        int x = stack.pop();
        //每次弹出元素时都要和最小栈栈顶元素比较(注意peek返回的是对象,比较不能写成stack.peek()==minStack.peek())
        //此处用int == Integer,自动拆箱
        if(x==minStack.peek()){
            minStack.pop();
        }
    }

    public int top() {
        if(stack.isEmpty()){
            return -1;
        }
        return stack.peek();
    }

    public int getMin() {
        if(minStack.isEmpty()){
            return -1;
        }
        return minStack.peek();
    }
}
